package top.hkyzf.study.leetcode.array;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 朱峰
 * @date 2022-2-19 9:13
 */
public class 煎饼排序_969 {
    public List<Integer> pancakeSort(int[] arr) {
        int right = arr.length - 1;
        List<Integer> result = new ArrayList<>();
        while (right > 0) {
            int max = Integer.MIN_VALUE;
            int index = 0;
            for (int i = 0; i <= right; i++) {
                if (max < arr[i]) {
                    max = arr[i];
                    index = i;
                }
            }
            if (index != right) {
                result.add(index+1);
                result.add(right+1);
                reverse(arr, index, right);
            }
            right--;
        }
        return result;
    }

    private void reverse(int[] arr, int index, int right) {
        int l = 0, r = index, temp;
        if (index != 0) {
            while (r > l) {
                temp = arr[l];
                arr[l] = arr[r];
                arr[r] = temp;
                r--;
                l++;
            }
        }
        l = 0; r = right;
        while (r > l) {
            temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;
            r--;
            l++;
        }
    }

    @Test
    public void testPancakeSort () {
        int[] arr = {3,2,4,1};
        System.out.println(pancakeSort(arr));
    }
}
